var QRCode = require('../../utils/weapp-qrcode.js')
const util = require('../../utils/util.js');
var getQrCode = require('../../utils/QRcodenum.js')
console.log(getQrCode)
var qrcode;
const app = getApp().globalData;
const HttpAjax = getApp().getHttpData
function promisify(api) { //异步获取用户图片
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      const extras = {
        success: resolve,
        fail: reject
      }
      api({
        ...options,
        ...extras
      }, ...params)
    })
  }
}

Date.prototype.Format = function (fmt) {
  //author: meizz 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

let timer,clearTime;//定时器要清除的；

Page({
  data: {
    text: '',
    image: '',
    bg: '',
    avatarUrl: '',
    date: new Date().Format('yyyy-MM-dd').replace(/-/g, '/'),
    time: new Date().Format('hh:mm'),
    start: new Date().Format('yyyy-MM-dd'),
    starttime: new Date().Format('hh:mm'),
    userInfo: '',
    hasUserInfo: '',
    qrcodeError: false,
    qrcodedata: '88888888',
    canvasW: '',
    canvasH: '',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canvasWidth: '',
    canvasHeight: '',
    potocode: false, //显示二维码弹窗
    endtime: '',
    imagePath: '',
    error: '',
    visible2: false,
    multiArray: [['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'], ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59'], ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']],
    multiIndex: new Date().Format('hh:mm:ss').split(':').map((e) => { return e = e - 0 }),
    startmultiIndex: new Date().Format('hh:mm:ss').split(':').map((e) => { return e = e - 0 })
  },
  onLoad: function (options) { //页面加载完成时
    //第六次该需求。。。
    // console.log(45454545)
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res);
        let myCanvasWidth, myCanvasHeight;
        myCanvasWidth = res.windowWidth
        myCanvasHeight = res.windowHeight - 50

        that.setData({
          canvasW: res.windowWidth - 60,
          canvasH: res.windowWidth - 60,
          canvasWidth: myCanvasWidth,
          canvasHeight: myCanvasHeight
        })
      },
    })
    const wxGetImageInfo = promisify(wx.getImageInfo);
    // wxGetImageInfo({//缓存图片
    //   src: app.userInfo.avatarUrl
    // }).then(res => {
    //   // console.log(res)
    //   that.setData({
    //     avatarUrl: res.path
    //   })
    // }).catch(res => {
      that.setData({
        avatarUrl: './../../image/er.png'
      })
    // })
    let t = ``;
    this.data.bg = this.bg3()
    qrcode = new QRCode('canvas', { //生成二维码
      // usingIn: this,
      text: t,
      width: 260,
      height: 260,
      colorDark: this.data.bg,
      colorLight: "white",
      correctLevel: QRCode.CorrectLevel.H
    });
    let data = (Math.round(new Date().getTime() / 1000) + 300)*1000;
    let QRnum=88888888; 
    console.log(getQrCode.getQrCode)
    getQrCode.getQrCode(data,app.cardid,1).then(res=>{
      // console.log(res)
      QRnum=res;
      qrcode.makeCode(QRnum);
    }).catch(err=>{
      qrcode.makeCode(QRnum);
    });
    console.log(data,QRnum)
    
    setTimeout(() => {
      that.canvasToTempImage('canvas', 'image')
    }, 500);
    setTimeout(() => {
      that.setQRCode();
    }, 5000);
  },
  onReady: function () {
    
  },
  shareCode() { //弹出分享二维码
    // this.data.potocode=true
    this.setData({
      potocode: true
    })
    let that = this;
    // console.log(this.setCanvasSize())
    qrcode.exportImage(function (path) {

      // console.log(wxGetImageInfo)
      wx.showToast({
        title: '分享图片生成中...',
        icon: 'loading',
        duration: 20000
      });

      // console.log(that.data.canvasWidth)
      let canvaswidths = that.data.canvasWidth;
      let qrwidth = canvaswidths - 80;//二维码宽度
      const ctx = wx.createCanvasContext('shareCanvas');
      // ctx.drawImage(res.path, 0, 60, that.data.canvasWidth, 400)
      ctx.clearRect(0, 60, canvaswidths, canvaswidths*1.4);
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 60, canvaswidths, canvaswidths * 1.4);
      ctx.drawImage(path, (canvaswidths - qrwidth) / 2, 100, qrwidth, qrwidth) //二维码
      // console.log(app.userInfo.avatarUrl)
      ctx.drawImage(that.data.avatarUrl, (canvaswidths - 50) / 2, 60 + (canvaswidths - 50) / 2, 50, 50) //头像
      ctx.setTextAlign('center') // 文字居中
      ctx.setFillStyle('#000000') // 文字颜色：黑色
      ctx.setFontSize(18) // 文字字号：22px
      ctx.fillText('二维码有效期：' + that.data.endtime, canvaswidths / 2, canvaswidths*1.2)
      ctx.fillText('点击图片长按分享', canvaswidths / 2, canvaswidths * 1.2+20)

      ctx.fillText('二维码门禁', canvaswidths / 2, 90)
      ctx.stroke()
      ctx.draw()


      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            // console.log(tempFilePath);
            that.setData({
              imagePath: tempFilePath,
              // maskHidden: false
              // canvasHidden:true
            });
            wx.hideToast()
          },
          fail: function (res) {
            console.log(res);
          }
        });
      }, 500);

    })
  },
  //获取临时缓存照片路径，存入data中
  canvasToTempImage: function (canvasID,path) {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: canvasID,
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        // console.log(tempFilePath);
        let b={}
        b[path] = tempFilePath
        that.setData(b);
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  exit() { //退出弹窗
    // this.data.potocode=false
    wx.hideToast()
    this.setData({
      potocode: false
    })
  },
  onShow() { //页面显示时
    let that = this;
    wx.setScreenBrightness({
      value: 0.7,
      success: res => {
        // console.log(res)
      }
    })
    // debugger;
    console.log('8979797979877777777777776asdf',app.qrcodeRefres)
    if (app.qrcodeRefres) {//如果卡号更新再返回到本页面
      app.qrcodeRefres = false;
      this.tapHandler();
    } else {
      // setqrc()
      let ndate = Math.round(new Date().getTime() / 1000) ;
      let odate = wx.getStorageSync('savetime');
      let t=odate-ndate;
      if(t>=0){
        console.log(t)
      }else{
        that.setQRCode();
      }
    }
    function setqrc() {
      // console.log(4545)
      if (that.data.qrcodedata == '88888888') {
        setTimeout(() => {
          setqrc();
        }, 200)
      } else {
        setTimeout(() => {
          qrcode.makeCode(that.data.qrcodedata);
        }, 5000)
      }
    }
  },
  onHide() {
    console.log(clearTime);
    clearInterval(clearTime);
    wx.setScreenBrightness({
      value: 0.5,
      success: res => {
        // console.log(res)
      }
    })
  },
  confirmHandler: function (e) {
    var value = e.detail.value
    qrcode.makeCode(value)
  },
  inputHandler: function (e) {
    var value = e.detail.value
    this.setData({
      text: value
    })
  },
  tapHandler: function () { //刷新
    let that = this;
    this.setData({
      qrcodeError: false
    })
    that.setQRCode(Math.round(new Date().getTime() / 1000) + 300,300);
  },
  save: function () {//保存图片
    // console.log('save')
    let that = this;
    wx.showActionSheet({
      itemList: ['保存图片'],
      success: function (res) {
        // console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          qrcode.exportImage(function (path) {
            // console.log(path)
            wx.saveImageToPhotosAlbum({
              filePath: path,
            })
          })
        }
      }
    })
  },
  bg3() { //随机颜色
    // var r = Math.floor(Math.random() * 256);
    // var g = Math.floor(Math.random() * 200);
    // var b = Math.floor(Math.random() * 150);
    return "rgb(" + 0 + ',' +0 + ',' + 0 + ")";
  },
  onShareAppMessage(res) { // 来自页面内转发按钮
    if (res.from === 'button') {

      // console.log(res.target)
    }
    return {
      title: app.company,
      path: '/pages/login/index'
    }
  },
  bindDateChange(e) {
    // console.log(e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange(e) {
    // console.log(e.detail.value)
    this.data.time = e.detail.value
    this.setData({
      time: e.detail.value
    })
  },
  entertime() { //确定时间
    let that = this;
    let dataTime = this.data.date;
    dataTime = dataTime.replace(/-/g, '/');
    let mutTime = this.data.startmultiIndex.join(':');
    // console.log(dataTime, mutTime,513);
    // console.log(Math.round(new Date(dataTime + ' ' + mutTime).getTime() / 1000), Math.round(new Date().getTime() / 1000))
    if ((Math.round(new Date(dataTime + ' ' + mutTime).getTime() / 1000)) < Math.round(new Date().getTime() / 1000)) {
      wx.showToast({
        title: '所选时间不能小于现在时间',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.setStorageSync('savetime', Math.round(new Date(dataTime + ' ' + mutTime).getTime() / 1000))
      // console.log(wx.getStorageSync('savetime'),521);
      let t = wx.getStorageSync('savetime') - Math.round(new Date().getTime() / 1000)
      if (t > 2000000) {
        t = 2000000
      }
      that.setQRCode(wx.getStorageSync('savetime'),t);
    }
  },
  previewImg: function (e) { //点击大图
    var img = this.data.imagePath
    // console.log(e)
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  previewImg1: function (e) { //点击大图
    var img = this.data.image
    // console.log(e)

  },
  setTime() {
    this.setData({
      visible2: true,
    })
    wx.setScreenBrightness({
      value: 0.7,
      success: res => {
      }
    })
  },
  onClose2() {
    this.onClose('visible2')
  },
  close2() {
    let that = this;
    this.setData({
      visible2: false,
      startmultiIndex: that.data.multiIndex
    })
    // console.log(that.data.startmultiIndex)
    this.entertime();

    wx.setScreenBrightness({
      value: 0.7,
      success: res => {
      }
    })
  },
  onClose(key) {
    // console.log('onClose')
    this.setData({
      [key]: false,
    })
    wx.setScreenBrightness({
      value: 0.7,
      success: res => {
      }
    })
  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value,
      startmultiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    // var data = {
    //   multiArray: this.data.multiArray,
    //   multiIndex: this.data.multiIndex
    // };
    // data.multiIndex[e.detail.column] = e.detail.value;
    // this.setData(data);
  },
  changecancel(e) {
    // console.log(e)
    let that = this;
    this.setData({
      multiIndex: that.data.startmultiIndex
    })
  },
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      // var scale = 750 / 686;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth;
      var height = res.windowHeight;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  fast_setTime(e){
    // console.log(e.target.dataset.id);
    let id = e.target.dataset.id;
    
    let timems = new Date().getTime() + (id * 60000);
    // console.log(timems)
    // console.log(new Date(timems).Format('hh:mm:ss'))
    // console.log(new Date().Format('yyyy-MM-dd').replace(/-/g, '/'))
    let arrTime = (new Date(timems).Format('hh:mm:ss')).split(':')
    arrTime[0] = arrTime[0] - 0;
    arrTime[1] = arrTime[1] - 0;
    arrTime[2] = arrTime[2]- 0;
    let fmtTime = new Date().Format('yyyy-MM-dd');

    this.setData({
      date: fmtTime,
      visible2: false,
      startmultiIndex: arrTime,
      multiIndex:arrTime
    });
    this.entertime();
  },
  /**
   * 设置二维码  刷新  自动更新等
   * */
  setQRCode(time= (Math.round(new Date().getTime() / 1000)) + 300,srts=300){
    // time 有效期   srts  到几秒后刷新
    let that=this;
    function cb(time1 = (Math.round(new Date().getTime() / 1000)) + 300, srts1=300){
      // console.log(time1)
      wx.setStorageSync('savetime', time1);
      let arrat = new Date(time1*1000).Format('hh:mm:ss');
      // console.log(arrat)
      HttpAjax(app.url + '/MicroApp/QRCode', {
        timeStamp: time1,
        cardNumber: app.cardid
      }, 'post', app.headerCookie)
        .then(res => {
          // console.log(res);
          if (res.data.result == 1) {
            qrcode.makeCode(res.data.Data.QrCode);
            setTimeout(() => {

              that.canvasToTempImage('canvas', 'image')
            }, 800)
            clearInterval(clearTime);
            clearTime = setInterval(() => {
              cb();
            }, (srts1 * 1000) + 100)
          }
          if (res.data.result == 3) {
            getApp().Login(getcode)
          }
        })
        .catch(err=>{
          console.error(err)
        })
      let yy = new Date(time1*1000).Format('yyyy');
      let mm = new Date(time1 * 1000).Format('MM')
      let dd = new Date(time1 * 1000).Format('dd')
      let tt = new Date().Format('hh')
      let Minutes = new Date().Format('mm')
      let ss = new Date().Format('ss')


      let date1 = `${yy}/${mm}/${dd} ${arrat}`
      // console.log(date1)
      that.setData({
        date:`${yy}-${mm}-${dd}`,
        endtime: date1,
        multiIndex: arrat.split(':').map((e) => { return e = e - 0 }),
        startmultiIndex: arrat.split(':').map((e) => { return e = e - 0 })
      })

    }
    cb(time,srts);
  },
  // 
  cookie(){
    console.log(app.headerCookie)
    app.headerCookie=''
  }
})